package com.ansion.utils.storage;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

import androidx.annotation.WorkerThread;

import java.io.File;

public class BaseStorage {

    @WorkerThread
    public long getAvailableSize(Context context) {
        try {
            File file = getRootFileDir(context);
            StatFs statFs = new StatFs(file.getPath());
            long blockCount = statFs.getAvailableBlocksLong();
            long blockSize = statFs.getBlockSizeLong();
            return blockCount * blockSize;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public File getCacheFileDir(Context context) {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ?
                getExternalCacheFilesDir(context) : context.getCacheDir();
    }

    public File getRootFileDir(Context context) {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ?
                getExternalFilesDir(context) : context.getFilesDir();
    }

    private File getExternalFilesDir(Context context) {
        File dir = context.getExternalFilesDir((String) null);
        if (dir != null) {
            return dir;
        }

        return context.getFilesDir();
    }

    private File getExternalCacheFilesDir(Context context) {
        File dir = context.getExternalCacheDir();
        if (dir != null) {
            return dir;
        }

        return context.getCacheDir();
    }
}
